package com.huiquan.framework.utils;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

public class RequestParamUtil {

	/**
	 * 获取字段默认值为di的整数型
	 * 
	 * @param req
	 * @param string
	 * @param di
	 * @return
	 */
	public static Integer getIntegerDefaultDi(HttpServletRequest req, String string, Integer di) {

		String s = req.getParameter(string);
		Integer result = di;
		try {
			result = Integer.parseInt(s);
		} catch (Exception err) {

		}
		return result;
	}

	/**
	 * 获取字段默认值为di，不小于i的整数型
	 * 
	 * @param req
	 * @param string
	 * @param i
	 * @return
	 */
	public static Integer getIntegerDefaultDiLargeThanI(HttpServletRequest req, String string, Integer di, Integer i) {

		Integer result = getIntegerDefaultDi(req, string, di);
		if (result < i) {
			result = i;
		}
		return result;
	}

	/**
	 * 获取字段默认值为1的整数型
	 * 
	 * @param req
	 * @param string
	 * @return
	 */
	public static Integer getIntegerDefault1(HttpServletRequest req, String string) {
		return getIntegerDefaultDi(req, string, 1);
	}

	/**
	 * 获取字段默认值为1，不小于1的整数型
	 * 
	 * @param req
	 * @param string
	 * @param i
	 * @return
	 */
	public static Integer getIntegerDefault1LargeThan1(HttpServletRequest req, String string) {
		return getIntegerDefaultDiLargeThanI(req, string, 1, 1);
	}

	/**
	 * 参数中字符串都要trim
	 * 
	 * @param param
	 * @return
	 */
	public static String getTrimString(HttpServletRequest req, String paramKey) {
		String paramValue = req.getParameter(paramKey);
		if (paramValue == null || paramValue.isEmpty()) {
			return paramValue;
		} else {
			return paramValue.trim();
		}
	}

	/**
	 * 参数中字符串数组中trim
	 * 
	 * @param req
	 * @param paramKey
	 * @return
	 */
	public static String[] getTrimStringArray(HttpServletRequest req, String paramKey) {
		String[] paramValue = req.getParameterValues(paramKey);
		if (paramValue == null || paramValue.length == 0) {
			return paramValue;
		} else {
			Set<String> set = new HashSet<>();
			for (int i = 0; i < paramValue.length; i++) {
				set.add(paramValue[i].trim());
			}
			return (String[]) set.toArray(new String[set.size()]);
		}
	}

	public static String getParamByRequestOrSession(HttpServletRequest req, Map<String, Object> pageParam,
			String string) {
		String param = req.getParameter(string);
		if (param == null) {
			param = pageParam.get(string) == null ? null : pageParam.get(string).toString();
		} else {
			pageParam.put(string, param);
		}
		return param;
	}

	@SuppressWarnings("unchecked")
	public static String getParamBySession(HttpServletRequest req, String string) {
		Map<String, String> pageParam = (Map<String, String>) req.getSession().getAttribute("pageParam");
		return pageParam.get(string);
	}
}
